package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;


/**
 * @Author: Bright
 * @Date: 2022-04-13 17:01
 * @Description: com.atguigu.srb.core.listener
 * @version: 1.0
 */
@NoArgsConstructor
@Slf4j
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
    private DictMapper dictMapper;

    private final ArrayList<ExcelDictDTO> list = new ArrayList<>();
    private static final int BATCH_COUNT = 5;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        list.add(excelDictDTO);
        log.info("添加一条记录");
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
            log.info("达到五条，存入数据库");
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("收尾执行一次");
        saveData();
    }

    private void saveData() {
        dictMapper.batchImport(list);
    }
}
